import axios from 'axios';
import { getCookie } from '@/utils/cookie'
import message from '@/utils/message'
import { clog, isNull } from '@/utils'

// 消息弹框
export const ms = message
// 接口地址配置文件
declare const config: any

// create an axios instance
const service = axios.create({
  baseURL: config.BaseApiUrl + '/', // url = base url + request url
  // withCredentials: true, // 
  timeout: 5000 // request timeout//超时时间
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = getCookie('Token')
    if (token) {
      config.headers.common["Authorization"] = "Bearer " + token
    }
    //拦截器给参数添加表格头
    config.headers.common[".AspNetCore.Culture"] = "zh-hans";
    config.headers.common["Abp.TenantId"] = getCookie("Tenant", true) == null ? undefined : parseInt(getCookie("Tenant", true).id);
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    //401状态为未登陆，此时清除token刷新页面
    if (!!error.response && error.response.status === 401) {
      //location.reload();
    }
    if (!!error.response && !!error.response.data.error) {
      let errorData = error.response.data.error
      let msg = isNull(errorData.message) ? "" : errorData.message;
      let details = isNull(errorData.details) ? "" : errorData.details;
      let validation = isNull(errorData.validationErrors) ? "" : errorData.validationErrors;
      ms.error(msg + details + validation);
    } else {
      let errorInfo = clog(error)
      if (errorInfo.indexOf("Network") > 0) {
        ms.error("网络错误: " + error);
      } else if (errorInfo.indexOf("timeout") > 0) {
        ms.error("调用超时: " + error);
      } else {
        ms.error("调用接口失败: " + error);
      }
      return Promise.reject(error);
    }
  }
)

export default service
